<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Document extends CCMIS_Controller {

    public function __construct() {
        parent::__construct();


        $this->load->model('model_ccmisdepartment');
        $this->load->model('model_facultydocuments');
        $this->load->model('model_facultymember');
        $this->load->model('model_facultydocumentpublicity');
    }

    public function index()
    {
        $this->view();
    }

    public function view()
    {
        $depts = $this->model_ccmisdepartment->getAll();
        $docs = $this->model_facultydocuments->getByUploaderId($this->session->userdata('user_id'));
        $publicity = $this->model_facultydocumentpublicity->getAll();

        $docsNew = array();
        foreach($docs as $doc)
        {
            $docNew = $doc;

            $docNew['UploaderName'] = $this->model_facultymember->getNameAppendedById($doc['UploaderID']);
            $docNew['PublicityName'] = $this->model_facultydocumentpublicity->getDescById($doc['PublicityID']);


            array_push($docsNew, $docNew);
        }


        $data = array(
            'cb_document_name' => 'document_name_filter',
            'document_name' => '',
            'cb_uploader_name' => '',
            'uploader_name' => '',
            'cb_dept_filter' => '',
            'cb_dept' => '',
            'dept' => '',
            'departments' => $depts,
            'uploads_owner' => $docsNew, // Owner uploads
            'publicity' => $publicity,
            'uploads_search' => null, // Search of uploads

        );

        $this->setup_view('fmis/document/view', $data);
        return;
    }

    public function upload($type)
    {
        //page for uploading documents
        $config['upload_path'] = './uploads/fmis/documents/'.$this->session->userdata('user_id');
        $config['allowed_types'] = 'doc|docx|xls|xlsx|pdf|ppt|pptx|word|tex|latex|htm|html|rtf|txt';
        $config['file_name'] = $this->input->post('p_filerename');
        $config['overwrite'] = true;
        $config['remove_spaces'] = false;

        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        $this->load->library('user_agent');

        if( ! ($this->upload->do_upload($type))) {
            $data = array(
                'success' => false,
                'page_title' => 'Error',
                'message' => $this->upload->display_errors(),
                'referrer' => $this->agent->referrer()
            );
        }
        else {
            $uploaderID = $this->session->userdata('user_id');
            $documentName = $this->input->post('p_filerename');
            $date = date('Y/m/d h:i:s', time());
            $publicityID = 2;
            $originalName = $this->upload->data()['file_name'];
            $description = '';
            $documentType = $this->upload->data()['file_type'];

            $this->model_facultydocuments->add($uploaderID, $documentName, $date, $publicityID, $originalName, $description, $documentType);


            $data = array(
                'success' => true,
                'page_title' => 'Success',
                'message' => 'Your file has been successfully uploaded',
                'referrer' => $this->agent->referrer()
            );
        }


        echo json_encode($data);
        //$this->setup_view('fmis/document/upload',$data);
//*/
    }

    public function delete($id)
    {
        $data = array(
            'success' => false,
            'id'=>$id,
        );

        $documentName = $this->model_facultydocuments->getById($id)['DocumentName'];
        $uploaderId = $this->session->userdata('user_id');

        $file = './uploads/fmis/documents/'.$uploaderId.'/'.$documentName;

        if(file_exists($file))
        {
            unlink($file);
            $this->model_facultydocuments->deleteById($id);
            $data['success'] = true;
            $data['message'] = 'Document Deleted';
        }
        else
        {
            $data['success'] = false;
            $data['message'] = 'File Not Found';
        }

        echo json_encode($data);
    }

    public function download($id)
    {
        $documentName = $this->model_facultydocuments->getById($id)['DocumentName'];
        $uploaderId = $this->session->userdata('user_id');

        $file = './uploads/fmis/documents/'.$uploaderId.'/'.$documentName;

        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
        }

        /* THIS CODEIGNITER THING WON'T WORK
        $documentName = $this->model_facultydocuments->getById($id)['DocumentName'];
        $uploaderId = $this->session->userdata('user_id');

        $data = './uploads/fmis/documents/'.$uploaderId.'/'.$documentName;
        //set the textfile's name
        $name = 'CCMIS_Document_Download';
        //use this function to force the session/browser to download the created file

        echo $uploaderId;
        echo $documentName;

        echo force_download($name, $data);
        //*/
    }

    public function editdetail($id)
    {
        $documentName = trim($this->input->post('edit_document_name'));
        $publicity = $this->input->post('edit_document_publicity');
        $description = trim($this->input->post('edit_document_description'));

        $document = $this->model_facultydocuments->getById($id);
        $uploaderId = $document['UploaderID'];
        $previousDocumentName = $document['DocumentName'];

        $prevPath = './uploads/fmis/documents/'.$uploaderId.'/'.$previousDocumentName;
        $newPath =  './uploads/fmis/documents/'.$uploaderId.'/'.$documentName;

        $this->model_facultydocuments->editById($id, $documentName, $publicity, $description);
        rename($prevPath, $newPath);

        $data = array(
            'ext' => file_exists($prevPath),
            'ext2' => file_exists($newPath),
            'prev' => $prevPath,
            'new' => $newPath,
            'success' => true,
            'id' => $id,
            'documentName' => $documentName,
            'publicity' => $publicity,
            'description' => $description,
        );

        echo json_encode($data);

    }

    public function search()
    {
        $depts = $this->model_ccmisdepartment->getAll();
        $publicity = $this->model_facultydocumentpublicity->getAll();

        if($this->input->server('REQUEST_METHOD') === 'GET')
        {
            $publicID = $this->model_facultydocumentpublicity->getIdByDesc('Public');
            $docs = $this->model_facultydocuments->getAllByPublicity($publicID);
            $docsNew = array();
            foreach($docs as $doc)
            {
                $docNew = $doc;

                $docNew['UploaderName'] = $this->model_facultymember->getNameAppendedById($doc['UploaderID']);
                $docNew['PublicityName'] = $this->model_facultydocumentpublicity->getDescById($doc['PublicityID']);


                array_push($docsNew, $docNew);
            }

            $data = array(
                'cb_document_name' => 'document_name_filter',
                'document_name' => '',
                'cb_uploader_name' => '',
                'uploader_name' => '',
                'cb_dept' => '',
                'dept' => '',
                'departments' => $depts,
                'uploads_owner' => $docsNew, // Owner uploads
                'publicity' => $publicity,
                'uploads_search' => null, // Search of uploads

            );

            $this->setup_view('fmis/document/search', $data);
            return;
        }
        else
        {
            $documentname = $this->input->post('document_name_filter');
            $uploadername = $this->input->post('uploader_name_filter');
            $dept = $this->input->post('dept_filter');
            $cb_documentname = $this->input->post('cb_document_name_filter');
            $cb_uploadername = $this->input->post('cb_uploader_name_filter');
            $cb_dept = $this->input->post('cb_dept_filter');

            $documentname = $cb_documentname == 'document_name_filter' ? $documentname : '';
            $uploadername = $cb_uploadername == 'uploader_name_filter' ? $uploadername : '';
            $dept = $cb_dept == 'dept_filter' ? $dept : '';

            $uploadersByName = $this->model_facultymember->getAllByName($uploadername);
            $uploadersByDept = $this->model_facultymember->getAllByDeptId($dept);

            $idstring = "";
            foreach($uploadersByName as $uploader)
            {
                $id = $uploader['MemberID'];
                if (strpos($idstring, $id) !== false){}//INAANTOK NAKO NG GINAWA KO TO. SORRY
                else{
                    $idstring .= $id." ";
                }
            }
            foreach($uploadersByDept as $uploader)
            {
                $id = $uploader['MemberID'];
                if (strpos($idstring, $id) !== false){}//INAANTOK NAKO NG GINAWA KO TO. SORRY
                else{
                    $idstring .= $id." ";
                }
            }

            $uploaders = explode(' ', $idstring);
            $publicID = $this->model_facultydocumentpublicity->getIdByDesc('Public');

            $docs = $this->model_facultydocuments->search($documentname, $uploaders, $publicID);

            $docsNew = array();
            foreach($docs as $doc)
            {
                $docNew = $doc;

                $docNew['UploaderName'] = $this->model_facultymember->getNameAppendedById($doc['UploaderID']);
                $docNew['PublicityName'] = $this->model_facultydocumentpublicity->getDescById($doc['PublicityID']);

                array_push($docsNew, $docNew);
            }

            $data = array(
                'cb_document_name' => $cb_documentname,
                'document_name' => $documentname,
                'cb_uploader_name' => $cb_uploadername,
                'uploader_name' => $uploadername,
                'cb_dept' => $cb_dept,
                'dept' => $dept,
                'departments' => $depts,
                'uploads_owner' => $docsNew, // Owner uploads
                'publicity' => $publicity,
                'uploads_search' => null, // Search of uploads

            );

            $this->setup_view('fmis/document/search', $data);
            return;
            //*/
        }
    }

    //private functions
    private function getFileInfos()
    {

    }

}
